package com.z.ssmdemo.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class JwtLoginHandlerImpl implements LoginHandler {

    private static final String SECRET = "ggrewggh54h54h5";
    private static final String JWT_HEADER_KEY = "Authorization";
    @Override
    public void login(HttpServletRequest request, HttpServletResponse response, String userId) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //签发时间   数据
        String token = JWT.create().withIssuedAt(new Date()).withClaim("userId", userId).sign(algorithm);
        response.setHeader(JWT_HEADER_KEY,token);
    }

    @Override
    public boolean validateLogin(HttpServletRequest request) {
        String header = request.getHeader(JWT_HEADER_KEY);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT jWT = jwtVerifier.verify(header);
        //拿到签发时间
        Date issuedAt = jWT.getIssuedAt();
        String userId = jWT.getClaim("userId").asString();
        return userId!=null;

    }

    @Override
    public void loginOut(HttpServletRequest request, String username) {

    }
}
